﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SQLDataUploadHelper.commons.utils
{
    /// <summary>
    /// Http工具类
    /// </summary>
    public class HttpUtils
    {
        /// <summary>
        /// http POST
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="sendData">发送数据</param>
        /// <param name="reslut">结果</param>
        /// <returns></returns>
        public static bool HttpJsonPost(string url, string sendData, out string reslut)
        {
            reslut = "";
            try
            {
                byte[] data = System.Text.Encoding.Default.GetBytes(sendData);
                HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url);  // 制备web请求
                wbRequest.Proxy = null;     //现场测试注释掉也可以上传
                wbRequest.Method = "POST";
                wbRequest.ContentType = "application/json";
                wbRequest.ContentLength = data.Length;

                #region 
                //【2】将创建Stream流对象的过程写在using当中，会自动的帮助我们释放流所占用的资源。OK
                using (Stream wStream = wbRequest.GetRequestStream())         //using(){}作为语句，用于定义一个范围，在此范围的末尾将释放对象。
                {
                    wStream.Write(data, 0, data.Length);
                }
                #endregion

                //获取响应
                HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse();
                using (Stream responseStream = wbResponse.GetResponseStream())
                {
                    //using(){}作为语句，用于定义一个范围，在此范围的末尾将释放对象。
                    using (StreamReader sReader = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        reslut = sReader.ReadToEnd();
                    }
                }
            }
            catch (Exception e)
            {
                reslut = e.Message;     //输出捕获到的异常，用OUT关键字输出
                return false;              //出现异常，函数的返回值为
            }
            return true;
        }
    }
}
